/** auth.js
 module.exports = {
  login(email, pass, cb) {
    cb = arguments[arguments.length - 1]
    if (localStorage.token) {
      if (cb) cb(true)
      this.onChange(true)
      return
    }
    pretendRequest(email, pass, (res) => {
      if (res.authenticated) {
        localStorage.token = res.token
        if (cb) cb(true)
        this.onChange(true)
      } else {
        if (cb) cb(false)
        this.onChange(false)
      }
    })
  },

  getToken() {
    return localStorage.token
  },

  logout(cb) {
    delete localStorage.token
    if (cb) cb()
    this.onChange(false)
  },

  loggedIn() {
    return !!localStorage.token
  },

  onChange() {}
}

 function pretendRequest(email, pass, cb) {
  setTimeout(() => {
    if (email === 'joe@example.com' && pass === 'password1') {
      cb({
        authenticated: true,
        token: Math.random().toString(36).substring(7)
      })
    } else {
      cb({ authenticated: false })
    }
 }, 0)
 }
 */

const App = React.createClass({
    getInitialState() {
        return {
            loggedIn: auth.loggedIn()
        }
    },

    updateAuth(loggedIn) {
        this.setState({
            loggedIn
        })
    },

    componentWillMount() {
        auth.onChange = this.updateAuth;
        auth.login();
    },

    render() {
        return (
            <div>
                <ul>
                    <li>
            {this.state.loggedIn ? (
                <Link to="/logout">Log out</Link>
            ) : (
                <Link to="/login">Sign in</Link>
            )}</li>
                    <li><Link to="/dashboard">Dashboard</Link> (authenticated)</li>
                </ul>
        {this.props.children || <p>You are {!this.state.loggedIn && 'not'} logged in.</p>}
            </div>
        )
    }
})

// 权限拦截
const Login = React.createClass({

    getInitialState() {
        return {
            error: false
        }
    },

    handleSubmit(event) {
        event.preventDefault()

        const email = this.refs.email.value
        const pass = this.refs.pass.value

        auth.login(email, pass, (loggedIn) => {
            if (!loggedIn)
                return this.setState({ error: true })

            const { location } = this.props

            if (location.state && location.state.nextPathname) {
                this.props.router.replace(location.state.nextPathname)
            } else {
                this.props.router.replace('/')
            }
        })
    },

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label><input ref="email" placeholder="email" defaultValue="joe@example.com" /></label>
                <label><input ref="pass" placeholder="password" /></label> (hint: password1)<br />
                <button type="submit">login</button>
          {this.state.error && (
              <p>Bad login information</p>
          )}
            </form>
        )
    }
})

// 在权限拦截的时候，将本身要进入到的页面保存起来，并传到登录认证页面，在登录认证页面登录成功之后，将转到目录页面；
function requireAuth(nextState, replace) {
    if (!auth.loggedIn()) {
        replace({
            pathname: '/login',
            state: { nextPathname: nextState.location.pathname }
        })
    }
}

<Router history={browserHistory}>
<Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="login" component={Login} />
    <Route path="logout" component={Logout} />
    <Route path="about" component={About} />
    <Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
</Route>
</Router>


// 除了onEnter，还有onLeave方法
const Home =
    React.createClass({

        getInitialState() {
            return {
                isSaved: false
            }
        },

        componentDidMount() {
            console.log(this.state);
            this.props.router.setRouteLeaveHook(
                this.props.route,
                this.routerWillLeave
            )
        },

        routerWillLeave(nextLocation) {
            // 返回 false 会继续停留当前页面，
            // 否则，返回一个字符串，会显示给用户，让其自己决定
            if (!this.state.isSaved)
                return '确认要离开？';
        },

        render() {
            return <div>Home</div>;
        }
    });